<?php

namespace app\services\activity;

use app\dao\activity\ActivityDao;
use app\model\activity\Activity;
use app\services\BaseServices;
use app\services\product\product\StoreCategoryServices;
use crmeb\exceptions\AdminException;

class ActivityService extends BaseServices
{
    public function __construct(ActivityDao $dao)
    {
        $this->dao = $dao;
    }


//
    public function getlist()
    {

        $activities = Activity::where('is_del', 0)->where('status', 1)
            ->order('is_top desc')->order('id desc')->paginate();


        $list = [];
        $cateIds = implode(',', array_column($activities->items(), 'cate_id'));
        /** @var StoreCategoryServices $categoryService */
        $categoryService = app()->make(ActivityCategoryService::class);
        $cateList = $categoryService->getCateParentAndChildName($cateIds);
        $preantCateList = $categoryService->getColumn([
            ['id', 'in', $cateIds]
        ], 'cate_name', 'id');
        foreach ($activities->items() as $activity) {
            $cateName = array_filter($cateList, function ($val) use ($activity) {
                if (in_array($val['id'], explode(',', $activity['cate_id']))) {
                    return $val;
                }
            });
            $cate_name = [];
            foreach ($cateName as $k => $v) {
                $cate_name[] = $v['one'] . '/' . $v['two'];
            }
            if (!count($cate_name) && isset($preantCateList[$activity['cate_id']])) {
                $cate_name[] = $preantCateList[$activity['cate_id']];
            }

            $activity->cate_name = is_array($cate_name) ? implode(',', $cate_name) : '';
            $list[] = $activity;
        }

        return [
            'list' => $list,
            'count' => $activities->count()
        ];
    }


    public function getDetail($id)
    {
        $activity = $this->dao->getOne(['id' => $id], 'id,banner,start_time,end_time,title,content,description,cate_id');
        if (!$activity) {
            throw new AdminException(410057);
        }
        $categoryService = app()->make(ActivityCategoryService::class);
        $cateList = $categoryService->getCateParentAndChildName($activity->cate_id);
        $cateName = array_filter($cateList, function ($val) use ($activity) {
            if (in_array($val['id'], explode(',', $activity['cate_id']))) {
                return $val;
            }
        });
        $cate_name = [];
        foreach ($cateName as $k => $v) {
            $cate_name[] = $v['one'] . '/' . $v['two'];
        }
        if (!count($cate_name) && isset($preantCateList[$activity['cate_id']])) {
            $cate_name[] = $preantCateList[$activity['cate_id']];
        }
        $activity->cate_name = implode(',', $cate_name);
        return $activity->toArray();
    }


    public function getAdminList($params)
    {

        $title = $params['title'] ?? '';
        $activity_time = $params['activity_time'] ?? [];
        $status = $params['status'] ?? -1;
        if ($status == '') $status = -1;
        $time_status = $params['time_status'] ?? -1;
        if ($time_status == '') $time_status = -1;

        $cateIds = [];
        if (isset($params['cate_id']) && $params['cate_id']) {
            $activityCategory = app()->make(ActivityCategoryService::class);
            $cateIds = $activityCategory->getColumn(['pid' => $params['cate_id']], 'id');
        }
        if ($cateIds) {
            $cateIds[] = $params['cate_id'];
        }

        $activities = Activity::when($title, function ($query) use ($title) {
            $query->where('title', 'like', '%' . $title . '%');
        })->when(!empty($activity_time), function ($query) use ($activity_time) {
            $start_time = $activity_time[0] ?? 0;
            $end_time = $activity_time[1] ?? 0;
            if ($start_time) {
                $query->where('start_time', '>=', $start_time);
            }
            if ($end_time) {
                $query->where('end_time', '<=', $end_time);
            }
        })->when(!empty($cateIds), function ($query) use ($cateIds) {
            $query->whereIn('cate_id', $cateIds);
        })->when($time_status != -1, function ($query) use ($time_status) {
            if ($time_status == 0) {
                $query->where('start_time', '>', time());
            } else if ($time_status == 1) {
                $query->where('start_time', '<=', time())->where('end_time', '>', time());
            } else if ($time_status == 2) {
                $query->where('end_time', '<=', time());
            }
        })->when($status != -1, function ($query) use ($status) {
            $query->where('status', $status);
        })->where('is_del', 0)->order('is_top desc')->order('id desc')->paginate($params['limit'] ?? 15);

        $list = [];
        $cateIds = implode(',', array_column($activities->items(), 'cate_id'));
        /** @var StoreCategoryServices $categoryService */
        $categoryService = app()->make(ActivityCategoryService::class);
        $cateList = $categoryService->getCateParentAndChildName($cateIds);
        $preantCateList = $categoryService->getColumn([
            ['id', 'in', $cateIds]
        ], 'cate_name', 'id');

        foreach ($activities as $activity) {
            $time_status = 0;
            if ($activity->start_time <= time() && $activity->end_time > time()) {
                $time_status = 1;
            }
            if ($activity->end_time <= time()) {
                $time_status = 2;
            }


            $cateName = array_filter($cateList, function ($val) use ($activity) {
                if (in_array($val['id'], explode(',', $activity['cate_id']))) {
                    return $val;
                }
            });
            $cate_name = [];
            foreach ($cateName as $k => $v) {
                $cate_name[] = $v['one'] . '/' . $v['two'];
            }
            if (!count($cate_name) && isset($preantCateList[$activity['cate_id']])) {
                $cate_name[] = $preantCateList[$activity['cate_id']];
            }


            $list[] = [
                'id' => $activity->id,
                'title' => $activity->title,
                'start_time' => $activity->start_time,
                'end_time' => $activity->end_time,
                'time_status' => $time_status,
                'cate_name' => is_array($cate_name) ? implode(',', $cate_name) : '',
                'type' => $activity->type,
                'type_jifen'    =>  $activity->type_jifen,
                'type_people'   =>  $activity->type_people,
                'status' => $activity->status,
                'is_top' => $activity->is_top
            ];
        }

        $count = $activities->count();

        return compact('list', 'count');
    }


    public function detail($id)
    {
        $activity = Activity::where('id', $id)->find();
        if (!$activity) return [];

        return [
            'id'    =>  $id,
            'title'=> $activity->title,
            'start_time'=> $activity->start_time,
            'end_time'=> $activity->end_time,
            'status' => $activity->status,
            'cate_id' => ($activity->cate_id) ? explode(',', $activity->cate_id) : [],
            'type' => $activity->type,
            'type_jifen' => $activity->type_jifen,
            'type_people' => $activity->type_people,
            'comon_rate' => $activity->comon_rate,
            'banner' => $activity->banner,
            'description' => $activity->description,
            'content' => $activity->content
        ];
    }

    public function save($id, $params)
    {
        $title = $params['title'] ?? '';
        $start_time = $params['start_time'] ?? 0;
        $end_time = $params['end_time'] ?? 0;
        $status = $params['status'] ?? 0;
        $cate_id = $params['cate_id'] ?? 0;
        $type = $params['type'] ?? 1;
        $type_jifen = $params['type_jifen'] ?? 0;
        $type_people = $params['type_people'] ?? 0;
        $comon_rate = $params['comon_rate'] ?? 0;
        $banner = $params['banner'] ?? '';
        $description = $params['description'] ?? '';
        $content = $params['content'] ?? '';

        if (!$title) throw new AdminException(30023);
        if (!$start_time || !$end_time) throw new AdminException(30024);
        if ($start_time > $end_time) throw new AdminException(30025);
        if (!$cate_id) throw new AdminException(30026);
        if (!$type) throw new AdminException(30027);
        if (!$comon_rate) throw new AdminException(30028);
        if (!$banner) throw new AdminException(30029);
        if ($type == 2 && !$type_jifen) throw new AdminException(30030);
        if ($type == 3 && !$type_people) throw new AdminException(30031);
        if (!$description) throw new AdminException(30032);
        if (!$content) throw new AdminException(30033);
        if (!in_array($status, [1, 0])) throw new AdminException(30034);

        $type_jifen = ($type == 2) ? $type_jifen : 0;
        $type_people = ($type == 3) ? $type_people : 0;

        $data = [
            'title' => $title,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'status' => $status,
            'cate_id' => !empty($cate_id) ? implode(',', $cate_id) : '',
            'type' => $type,
            'type_jifen' => $type_jifen,
            'type_people' => $type_people,
            'comon_rate' => $comon_rate,
            'banner' => $banner,
            'description' =>$description,
            'content'   =>  $content
        ];


        if ($id) {
            $this->dao->update($id, $data);
        } else {
            $data['add_time'] = time();
            $this->dao->save($data);
        }

        return true;
    }

    public function setShow($ids, $status)
    {
        $this->dao->batchUpdate($ids, ['status' => $status]);
        return true;
    }

    public function setTopStatus($ids, $is_top)
    {
        $this->dao->batchUpdate($ids, ['is_top' => $is_top]);
        return true;
    }

    public function delete($id)
    {
        $res = $this->dao->update($id, ['is_del' => 1]);
        if (!$res) throw new AdminException(100008);
    }

}